package com.xes.recognitiondemo;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Path;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.xes.hardwritingrecognition.HWRecognizer;
import com.xes.hardwritingrecognition.MainExecutor;

/**
 * @author wl
 * @since 2018/07/04 18:56
 */
public class MainActivity extends AppCompatActivity {
    private static final int REQUEST_EXTERNAL_STORAGE = 576;
    private static final int REQUEST_BROWSER_FILE = 381;

    private TextView tv_result;
    private HWRecognizer recognizer;
    private HandWriteView hwv_view;
    private SeekBar seek_bar;
    private TextView tv_paint_stroke;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        hwv_view = findViewById(R.id.hwv_view);
        tv_result = findViewById(R.id.tv_result);
        seek_bar = findViewById(R.id.seek_bar);
        tv_paint_stroke = findViewById(R.id.tv_paint_stroke);

        hwv_view.setOnDrawListener(new HandWriteView.OnWriteListener() {
            @Override
            public void onWriteStart() {

            }

            @Override
            public void onWritePause(Path path) {
                String r = recognizer.addPath(path);
                tv_result.append(r + " ");
            }
        });
        seek_bar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                hwv_view.setStrokeSize(progress);
                tv_paint_stroke.setText("画笔(" + seek_bar.getProgress() + ")");
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        seek_bar.setProgress(HandWriteView.DEFAULT_STROKE_WIDTH);
        // HWR
        HWRecognizer.DEBUG_MODE = false;
        recognizer = new HWRecognizer(this, "modelnew_cpu.pt", MainExecutor.ClassifierType.PyTorch);
    }

    private void verifyStoragePermissions() {
        try {
            int permission = ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if (permission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        REQUEST_EXTERNAL_STORAGE);
            } else {
                browserFile();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void recognize(View view) {
//        String str = recognizer.start();
//        tv_result.setText(str);

        // deprecated methods
        Bitmap tmpBitmap = hwv_view.getCurrentBitmap();
        String str2 = recognizer.start(tmpBitmap);
        Toast.makeText(this, str2, Toast.LENGTH_SHORT).show();
    }

    public void clear(View view) {
        tv_result.setText("");
        hwv_view.clearDraw();
        recognizer.clearPaths();
    }

    public void reverse(View view) {
        hwv_view.reverse();
        tv_result.setText("");
        recognizer.clearPaths();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (recognizer != null) {
            recognizer.destroy();
            recognizer = null;
        }
    }

    public void importFile(View view) {
        verifyStoragePermissions();
    }

    private void browserFile() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");//无类型限制
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent, REQUEST_BROWSER_FILE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == REQUEST_EXTERNAL_STORAGE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                browserFile();
            } else {
                Toast.makeText(this, "没有sd卡权限", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_BROWSER_FILE && resultCode == RESULT_OK) {
            Uri uri = data.getData();
            String path = UriUtils.parseFileUriToPath(this, uri);
            Bitmap bitmap = BitmapFactory.decodeFile(path);
            if (bitmap != null) {
                String str = recognizer.start(bitmap);
                tv_result.setText(str);
            } else {
                Toast.makeText(this, "无法识别的文件", Toast.LENGTH_SHORT).show();
            }
        }
    }
}
